Scroll Progress Bar

Matrix Transpose

Matrix transpose is an operation that converts the rows of a matrix into columns, and vice versa. For an MxN matrix, the transpose will be an NxM matrix. Each element in the original matrix is swapped with the element in the transposed matrix with the same row and column index.

Usage and Approach:

To perform a matrix transpose in C, can use a nested loop to iterate through each element of the matrix and swap the elements at corresponding positions. It is important to note that the transpose of a matrix can be performed in-place without requiring additional memory.

Sample Code with Explanation and Output:

#include <stdio.h>

#define ROWS 3
#define COLS 3

void transposeMatrix(int matrix[ROWS][COLS]) {
    int temp;
    for (int i = 0; i < ROWS; i++) {
        for (int j = i + 1; j < COLS; j++) {
            // Swap the elements at (i, j) and (j, i)
            temp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = temp;
        }
    }
}

void displayMatrix(int matrix[ROWS][COLS]) {
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            printf("%d\t", matrix[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int matrix[ROWS][COLS] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    printf("Original Matrix:\n");
    displayMatrix(matrix);

    // Transpose the matrix
    transposeMatrix(matrix);

    printf("\nTransposed Matrix:\n");
    displayMatrix(matrix);

    return 0;
}
Output:

Original Matrix:
1       2       3
4       5       6
7       8       9

Transposed Matrix:
1       4       7
2       5       8
3       6       9

Explanation:

In the sample code, define a 3x3 matrix named matrix and initialize it with values.

Define two functions:

transposeMatrix: This function performs the matrix transpose operation. It uses a nested loop to swap the elements at positions (i, j) and (j, i) for all elements in the upper triangular part of the matrix (above the main diagonal). Since the matrix is symmetric along the main diagonal, swapping the elements in the upper triangular part effectively transposes the entire matrix. displayMatrix: This function is used to display the matrix on the screen. It uses nested loops to print each element of the matrix. In the main function, print the original matrix using the displayMatrix function.

Next, call the transposeMatrix function to perform the transpose operation in-place on the matrix.

Finally, print the transposed matrix using the displayMatrix function.

The output shows the original matrix and its transpose. You can see that the rows of the original matrix become the columns of the transposed matrix, and vice versa.


What is the result of swapping rows and columns in a matrix?


Transpose

What is the main operation performed in matrix transpose?


Swapping

What is the shape of a matrix after performing transpose?


Rectangular